package top.cardone.context.func;

import lombok.Setter;
import org.apache.commons.collections.MapUtils;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.core.convert.converter.Converter;
import top.cardone.core.util.func.Func0;
import top.cardone.core.util.func.Func1;
import top.cardone.core.util.func.Func2;

import java.util.Map;

/**
 * @author yao hai tao
 * @date 2016/4/20
 */
public class DefaultValueFunc implements Func0<Object>, Func1<Object, Map<String, Object>>, Func2<Object, Map<String, Object>, Object> {
    @Setter
    private String defaultValue;

    @Setter
    private Converter converter;

    @Override
    public Object func(Map<String, Object> map, Object obj) {
        if (obj instanceof Map) {
            return this.func(map, (Map<String, Object>) obj);
        }

        return obj;
    }

    public Object func(Map<String, Object> map, Map<String, Object> params) {
        String key = MapUtils.getString(params, "key");

        if (StringUtils.isBlank(key)) {
            return MapUtils.getObject(params, "defaultValue");
        }

        Object val = MapUtils.getObject(map, key);

        if (val instanceof String) {
            if (StringUtils.isNotBlank((String) val)) {
                return val;
            }

            return MapUtils.getObject(params, "defaultValue");
        }

        Object value = ObjectUtils.defaultIfNull(val, MapUtils.getObject(params, "defaultValue"));

        map.put(key, value);

        return value;
    }

    @Override
    public Object func() {
        if (this.converter == null) {
            return this.defaultValue;
        }

        return converter.convert(defaultValue);
    }

    @Override
    public Object func(Map<String, Object> stringObjectMap) {
        return this.func();
    }
}